/*
 * @lc app=leetcode.cn id=331 lang=javascript
 *
 * [331] 验证二叉树的前序序列化
 */

// @lc code=start
/**
 * @param {string} preorder
 * @return {boolean}
 */
var isValidSerialization = function (preorder) {
  const size = preorder.length;
  let slots = 1;
  let i = 0;
  while (i < size) {
    if (slots === 0) {
      return false;
    }
    let char = preorder[i];
    if (char === ',') {
      i++;
    } else if (char === '#') {
      slots--;
      i++;
    } else {
      // 读取数字，可能是多位数
      while (preorder[i] !== ',' && i < size) {
        i++;
      }
      slots = slots - 1 + 2;
    }
  }
  return slots === 0;
};
// @lc code=end
